import { NextResponse } from 'next/server';
import { getServerSession } from 'next-auth/next';
import { authOptions } from '@/app/api/auth/[...nextauth]/route';
import { api } from '@/lib/apiService';

export async function GET(request, { params }) {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user?.email) {
      return NextResponse.json({ error: '未授权' }, { status: 401 });
    }
    
    const { id } = params;
    
    // 调用Python后端的获取单个模板API - 使用带认证的方法
    const response = await api.auth.get(`templates/${id}`);
    
    return NextResponse.json(response);
  } catch (error) {
    console.error('Database error:', error);
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}

export async function PUT(request, { params }) {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user?.email) {
      return NextResponse.json({ error: '未授权' }, { status: 401 });
    }
    
    const { id } = params;
    const data = await request.json();
    
    // 调用Python后端的更新模板API - 使用带认证的方法
    const response = await api.auth.put(`templates/${id}`, data);
    
    return NextResponse.json(response);
  } catch (error) {
    console.error('Server error:', error);
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}

export async function DELETE(request, { params }) {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user?.email) {
      return NextResponse.json({ error: '未授权' }, { status: 401 });
    }
    
    const { id } = params;
    
    // 调用Python后端的删除模板API - 使用带认证的方法
    const response = await api.auth.delete(`templates/${id}`);
    
    return NextResponse.json(response);
  } catch (error) {
    console.error('Server error:', error);
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}
